function detectAccordionSwitcher(){
	var qs = window.location.search;
	// Get the id from the request URL
	var id = qs.match(/\?.*?d=(\d)/);

	if(id != null){
		activateAccordion(id[1]-1);
	}
}

function setUpButtons(){
	$('#PBCreateChartLink').bind('click', function(){
		window.location = "builder";
	});
	
	$('#PBSearchLink').bind('click', function(){
		window.location = "search";
	});
	
	$('#charts_viewMore').bind('click', function(){
		window.location = "chartlist";
	});
	
	$('#books_viewMore').bind('click', function(){
		window.location = "booklist";
	});

	$('#groups_viewMore').bind('click', function(){
		window.location = "grouplist";
	});
	
	$('#manage_institutions').bind('click', function(){
		manageInstitutions();
	});
	
	$('#manage_groups').bind('click', function(){
		manageGroups();
	});
	
	// Create the accordion on the homepage.
	$("#PBaccHolder").accordion({fillSpace: true});
	
	$('#PBCreateBookLink').bind('click', function(){
		getFragment("createbook", function(data){
			// Show the user the dialog box.
			jQuery.facebox(data);
			
			// Bind the apply button.
			$("#PBButtonCheckCreateBook").bind('click', function(){
			
				var newBook = {
					name: $('#bookName').val(),
					description: $('#bookDescription').val(),
					visibility: $('input[type=radio][name=bookVisibility]:checked').val(),
					type: 'personal'
				};

				// Has the user inputted all the data that is required?
				if(newBook.name != "" && newBook.visibility != ""){
					// Send the data off to the server.
					$.ajax({
						type: "POST",
						url: PicBoard.baseURL + "rsrc.php?req=createBook",
						data: newBook,
						dataType: 'json',
						success: function(data){
							
							if(data.statusCode == '200'){
								window.location = "book?id=" + data.payload.bookID;
							}
						}				
					});
				} else {
					// The user has not added all of the required information
					alert("Please fill in all required fields.");
				}
			});
		
		});
	});
	
	// Link the create group button to the controller.
	$("#PBCreateGroupLink").bind('click', function(){
		getFragment("creategroup", function(data){
			// Display the form in facebox.
			jQuery.facebox(data);
			
			// Get the institutions the user is enrolled in & add to dropdown
			for(inst in PicBoard.institutions){ 
				// Populate the institution list
				if(PicBoard.institutions[inst]['instID'] != 1) $('#instOwnership').append( $("<option>", { value: PicBoard.institutions[inst]['instID'], text: PicBoard.institutions[inst]['name'] }) );
			}
			
			// Link the create button
			$("#PBButtonCheckCreateGroup").bind('click', function(){
				// Check with the remote server if the group already exists.
				
				var newGroup = {
					groupName: $('#groupName').val(),
					groupDescription: $('#groupDescription').val(),
					groupVisibility: $('input[type=radio][name=groupVisibility]:checked').val(),
					institution: $('#instOwnership').val()
				};
				
				// Has the user inputted all the data that is required?
				if(newGroup.groupName != "" && newGroup.groupVisibility != "" && newGroup.institution != ""){
					// Send the data off to the server.
					$.ajax({
						type: "POST",
						url: PicBoard.baseURL + "rsrc.php?req=createGroup",
						data: newGroup,
						dataType: 'json',
						success: function(data){
							if(data.statusCode == 200){
								window.location = "group?id=" + data.groupID;
							}
						}				
					});

				} else {
					// The user has not filled in all required fields.
					PicBoard.getTranslations(['lang_272_fillInFields'], function(data){
						alert(data.payload.lang_272_fillInFields);
					});
				}
				
			});
			
		});
		
	});
	
	$('.share_link').button({ icons: { primary: 'ui-icon-share' }})
		.bind('click', function(){ shareWithAFriend(this) });
	
	$('.addUserToInst').bind('click', function(){ addUserToInst( $(this).attr('id').substring(4) ) });
	
	$('#imagesets_add').bind('click', function(){
	
		if($('.ui-accordion-content:last').children('.loadItem').length > 0){
			$.ajax({url: PicBoard.baseURL + 'rsrc.php?req=getUploadDialog', 
				success: function(data){
					jQuery.facebox(data);
					// IE sucks
					if($.browser.msie != true) $('button').button();
					
					$('input[type=file][name=image]').change(function(){
						fileSplit = $('input[type=file]').val().match(/(.*?)\.[\w]{2,4}$/);
						$('input[name=fileName]').val(fileSplit[1]);
					});
					
					$('#uploadFileButton').bind('click', function(){
						// Get the filename
						filetype = $('input[type=file]').val().match(/\.(\w{2,4})$/);
						
						if($('input[type=file]').val() == ""){
							PicBoard.getTranslations(['lang_226_invalidFiletype'], function(data){
								alert(data.payload.lang_226_invalidFiletype);
							});					
						} else {
							filetype = filetype[1].toLowerCase();

							if(filetype == "png" || filetype == "jpg" || filetype == "jpeg" || filetype == "gif"){
								$("#uploadForm").submit();
							} else {
								PicBoard.getTranslations(['lang_226_invalidFiletype'], function(data){
									alert(data.payload.lang_226_invalidFiletype);
								});
							}
						}
					});
				}
			});
		} else {
			PicBoard.getTranslations(['lang_271_addImageSetFirst'], function(data){
				alert(data.payload.lang_271_addImageSetFirst);
			});
		}
	});
	
	$('#imagesets_create').bind('click', function(){
		getFragment("newImageset", function(data){
			jQuery.facebox(data);
			
			$('#saveImageset').bind('click', function(){
				$.post(PicBoard.baseURL + 'rsrc.php?req=createImageSet',$('#uploadForm').serialize(), function(data){
					if(data.statusCode == 200){
						window.location = "home";
					} else {
						jQuery.facebox(data.message);
					}
				}, 'json');				
			});
		});
		
	});
	
}

function shareWithAFriend(ref){
	getFragment('shareDialog', function(data){
		jQuery.facebox(data);
		
		itemDescription = $(ref).parents('.loadItem').find('.itemDescription');
		
		id = itemDescription.children('a:eq(0)').attr('href').match(/\?.*?id=(\w+)/);
		
		$('#shareDialog > #shareMediaInfo').append(
			$(ref).parents('.loadItem').find('.itemIcon > img, .itemIcon > embed').clone().css( {'height': '50px', 'width':'50px'} ),
			$("<h3>", { html: itemDescription.children('a:eq(0)').html() }),
			$("<p>", { html: itemDescription.children('p:last').html() })
		);
		
		$('#sendToContainer').data('users', { chartID: id[1], count:0, list: [] });
		
		$('#emailAddress').focus();
		
		$('#addEmailAddress').bind('click', function(){
			
			email = $('#emailAddress').val();
			if(/\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/.test(email)){
				
					$('#sendToContainer').append( $("<img>", { src: PicBoard.baseURL + 'images/loading_fb.gif', id: 'waitingImage' }) );
					$.post(PicBoard.baseURL + "rsrc.php?req=validateUsername", { 'email': email }, function(data){
						
						$('#waitingImage').remove();
						
						if(data.statusCode == 200){
							if($('#personPlaceholder').length > 0){
								$('#sendToContainer').html( $("<p>", { html: $('#emailAddress').val() }) );
							} else {
								$('#sendToContainer').append( $("<p>", { html: $('#emailAddress').val() }) );				
							}
							
							$('#sendToContainer').data('users').count++;
							$('#sendToContainer').data('users').list.push(email);
							
							if($('#sendToContainer').data('users').count > 0) {
								$('#sendMediaRequest').button('enable');
								if($.browser.msie) $('#sendMediaRequest').removeAttr('disabled');
							}
							
							$('#emailAddress').val("");
							$('#emailAddress').focus();
							email = "";
						} else {
							alert("This user does not exist in PicBoard.");
						}
						
									
					}, 'json');


			}
		});
		
		$('#sendMediaRequest').bind('click', function(){
			
			$.post(PicBoard.baseURL + "rsrc.php?req=shareMedia", $('#sendToContainer').data('users'), function(data){
				if(data.statusCode == 200){
					jQuery.facebox("Chart shared!");
				} else {
					jQuery.facebox(data.message);
				}
			}, 'json');

		});
	});
}

function manageGroups(){
	getFragment("manageGroups", function(data){
		jQuery.facebox(data);
		
		$('#managedGroupsHolder').html("");
		
		$.each(PicBoard.managedGroups, function(i, v){
			currGroup = this;
			
			$('#managedGroupsHolder').append(
				$("<div />", { style: "margin:10px;" }).html(
					$("<button>", { text: $('#removeText').val() + " " + currGroup[1], click: function(){ removeThisGroup(this) } }).data('groupInfo', currGroup)
				)
			);
		});
	});
}

function manageInstitutions(){
	getFragment("manageInstitutions", function(data){
		jQuery.facebox(data);
		$('#institutionsAccordion').accordion();
		
		// Get the current list of institutions and add it to the dialog so the user can remove
		$('#currentInstList').html("");

		$.each(PicBoard.institutions, function(i, v){
			instName = this.name;
			currInst = this;
			if(instName != "Global" && currInst.admin == "1"){
				$('#currentInstList').append(
					$("<div />", { style: "margin:10px;" }).html(
						$("<button>", { text: $('#removeText').val() + " " + instName, click: function(){ removeThisInst(this) } }).data('instInfo', currInst)
					)
				);
			}
		});

		$('button#createInstitution').bind('click', function(){
			$.post(PicBoard.baseURL + "rsrc.php?req=addInstitution", $('form#createInstForm').serialize(), function(data){
				if(data.statusCode == 200){
					window.location = "home";
				} else {
					alert(data.message);
				}
			}, 'json');		
		});

	});
}

function removeThisGroup(tar){
	// Prompt the user to see if they are sure that they want to remove this group
	var confirmed = confirm($('#removeConfirm').val());
	
	if(confirmed){
		$.post(PicBoard.baseURL + "rsrc.php?req=removeGroup", { id: $(tar).data('groupInfo')[0] }, function(data){
			if(data.statusCode == 200){
				window.location = "home";
			} else {
				alert(data.message);
			}
		}, 'json');		

	}
}

function removeThisInst(tar){
	
	// Prompt the user to see if they are sure that they want to remove this institution
	var confirmed = confirm($('#removeConfirm').val());
	
	if(confirmed){
	
			$.post(PicBoard.baseURL + "rsrc.php?req=removeInstitution", $(tar).data('instInfo'), function(data){
				if(data.statusCode == 200){
					window.location = "home";
				} else {
					alert(data.message);
				}
			}, 'json');		

	}
	
}

function addUserToInst(id){
	getFragment("addUsersToInst", function(data){
		jQuery.facebox(data);
			
			
		// Bind any remove buttons that we create to remove that row.
		$('.removeUserButton').live('click', function(){
			$(this).parent().parent().remove();
		});
		
		
		// Bind the add button to add a new row.
		$('#PBButtonAddInstUsers').bind('click', function(){
			if(/\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/.test($('#addEmail').val())){
			
			$.post(PicBoard.baseURL + "rsrc.php?req=validateUsername", { 'email': $('#addEmail').val() }, function(data){
					
					if(data.statusCode == 200){
						newEls = $(this).parent().parent().clone();
						
						newEls.find('input[id=addEmail]').replaceWith( newEls.find('input[id=addEmail]').val() );
						newEls.find('input[id=isAdmin]').replaceWith( (newEls.find('input[id=isAdmin]:checked').val() == null) ? "no" : "yes" );
						newEls.find('button[id=PBButtonAddInstUsers]').text('Remove').attr( {'id':'', 'class': 'removeUserButton'} );
						
						$(this).parent().parent().before(newEls);
						$('button').button();
						
						$('#addEmail').val("");
						$('#addEmail').focus();
					} else {
						alert("This user does not exist in PicBoard.");
					}
					
								
				}, 'json');

			}
		});

		// Confirm the added users and send to the server.		
		$('#PBButtonConfirmInstUsers').bind('click', function(){
			var sendObject = { 'id': id, 'data':[] };
			
			// Pull out the information from the table
			$('#addUsers > table > tbody > tr:gt(0)').each(function(){
				sendObject.data.push( { email: $(this).children("td:eq(0)").html(), admin: $(this).children("td:eq(1)").html() } );
			});
			
			sendObject.data.splice(sendObject.data.length -1, 1);
			
			jQuery.facebox("<div style='text-align:center; margin:5px'><img src='" + PicBoard.baseURL + "images/loading_fb.gif" + "' /><br />Applying changes...</div>");
			
			$.post(PicBoard.baseURL + "rsrc.php?req=addInstUsers", sendObject, function(data){
				jQuery.facebox(data.message);
				
				setTimeout(function(){
					jQuery.facebox(data.message);
					setTimeout(function(){ jQuery.facebox.close(); }, 1500)
				}, 1500);
			}, 'json');
			
		});
	});
}

function activateAccordion(level){
	$('#PBaccHolder').accordion( "activate" , level);
}

// Queue setUpButtons() to run when the document is ready.
PicBoard.addLoadEvent( "setUpButtons()" );
PicBoard.addLoadEvent( "detectAccordionSwitcher()" );
